<template>
  <el-card>
	<template #header>
      <h2>购买护理项目 - 客户【{{ customerName }}】</h2>
    </template>

    <!-- 搜索 -->
    <el-form :inline="true" class="toolbar">
      <el-form-item label="项目名">
        <el-input v-model="filters.name" placeholder="模糊搜索" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchAllProjects">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 可选项目列表 -->
    <el-table :data="allProjects" stripe style="margin-top:16px;">
      <el-table-column prop="name" label="项目名" />
      <el-table-column prop="price" label="价格" width="100" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="select(row)">添加</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 已选项目 -->
    <h3 style="margin-top:20px;">已选项目</h3>
    <el-table :data="selected" stripe>
      <el-table-column prop="name" label="项目名" />
      <el-table-column label="数量" width="200" class-name="el-table-column--quantity">
        <template #default="{ row }">
          <el-input-number v-model="row.quantity" min="1" />
        </template>
      </el-table-column>
      <el-table-column label="到期时间" width="260" class-name="el-table-column--expire">
        <template #default="{ row }">
          <el-date-picker
            v-model="row.expireDate"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" class-name="el-table-column--operation">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="deselect(row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 保存/取消 … -->
	<div style="margin-top: 20px; text-align: right;">
	  <el-button @click="cancel">取消</el-button>
	  <el-button type="primary" @click="save" :disabled="selected.length === 0" style="margin-left: 8px;">
	    确认
	  </el-button>
	</div>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import qs from 'qs'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const axios = inject('axios')
const route = useRoute()
const router = useRouter()

const customerId   = Number(route.query.customerId)
const customerName = route.query.customerName || ''

const filters     = reactive({ name: '' })
const allProjects = ref([])
const selected    = ref([])

async function fetchAllProjects() {
  const [{ data: prResp }, { data: haveResp }] = await Promise.all([
    axios.get('/CareProjectController/queryByStatus', {
      params: { name: filters.name, status: 1, cur: 1, number: 1000 }
    }),
    axios.get('/CustomerCarePlanController/searchCustomerCarePlan', {
      params: { customerId }
    })
  ])
  const existingCodes = new Set([
    ...haveResp.data.map(p => p.careProjectCode),
    ...selected.value.map(p => p.careProjectCode)
  ])
  allProjects.value = prResp.data.filter(p => !existingCodes.has(p.code))
}

function select(item) {
  const idx = allProjects.value.findIndex(p => p.code === item.code)
  if (idx === -1) return
  allProjects.value.splice(idx, 1)
  selected.value.push({
    customerId,
    careProjectCode: item.code,
    quantity: 1,
    expireDate: dayjs().add(3, 'month').format('YYYY-MM-DD'),
    name: item.name,
    price: item.price
  })
}

function deselect(item) {
  const idx = selected.value.findIndex(p => p.careProjectCode === item.careProjectCode)
  if (idx === -1) return
  selected.value.splice(idx, 1)
  allProjects.value.unshift({
    code: item.careProjectCode,
    name: item.name,
    price: item.price
  })
}

async function save() {
  for (const p of selected.value) {
    await axios.post(
      '/CustomerCarePlanController/addCustomerCarePlan',
      qs.stringify({
        customerId: p.customerId,
        careProjectCode: p.careProjectCode,
        purchaseDate: dayjs().format('YYYY-MM-DD'),
        quantity: p.quantity,
        expireDate: p.expireDate,
        status: 1,
		source: 2
      })
    )
  }
  ElMessage.success('添加成功')
  router.push({
    path: '/ServiceAttention',
    query: { customerId, customerName }
  })
}

function cancel() {
  router.back()
}

onMounted(fetchAllProjects)
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}
/* 给操作按钮和输入框多一点左右间隔 */
.el-table .el-table-column--operation .cell,
.el-table .el-table-column--quantity .cell,
.el-table .el-table-column--expire .cell {
  padding: 0 12px;
}
</style>
